import { View, Image, Text } from '@tarojs/components'

import './index.less'
import Taro from '@tarojs/taro'

interface BookBarProps {
  image_url: string
  title: string
  author: string
  description: string
  rating: number
  item: any
}

const BookBar = (props: BookBarProps) => {
  const { image_url, title, author, description, rating = 0, item } = props

  const getStarSum = (num: number) => {
    const length = Math.floor(String(num) == 'N/A' ? 80/ 10 / 2  : num/ 10 / 2)
    return (
      Array.from({ length: length }, () => 1)?.map((item, index) => (
        <Image key={index} className='bookStar' src={require('../../assets/rating.png')}></Image>
      )) ?? []
    )
  }

  function truncateString(str, maxLength) {
    if (str.length > maxLength) {
      return str.slice(0, maxLength - 3) + '...'
    }
    return str
  }

  const hanldeClickBook = (item) => {
    Taro.navigateTo({ url: '/pages/book-detail/index?id=' + item.bookId })
  }

  return (
    <View className='bookbar' onClick={() => hanldeClickBook(item)}>
      <View>
        <Image className='bookImage' src={item.imageUrl}></Image>
      </View>

      <View className='bookContent'>
        <View className='bookTitle'>
          <Text className='bookTitleMain'>{truncateString(item.name, 12)}</Text>
          <Text className='bookTitleAuhtor'>{truncateString(item.author, 12)}</Text>
        </View>

        <View className='bookContentMain'>{item.dscript}</View>

        <View className='bookTextBar'>
          <View className='startList'>{getStarSum(item.rating)}</View>
          <Text className='bookText'>去阅读</Text>
        </View>
      </View>
    </View>
  )
}

export default BookBar
